package tgc.edu.ljc.layui.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import tgc.edu.ljc.layui.custom.CommonService;
import tgc.edu.ljc.layui.entity.Course;
import tgc.edu.ljc.layui.entity.Grade;
import tgc.edu.ljc.layui.entity.Stu;
import tgc.edu.ljc.layui.repository.CourseRepository;
import tgc.edu.ljc.layui.repository.GradeRepository;
import tgc.edu.ljc.layui.repository.StudentRepository;

@Service
public class GradeService extends CommonService<Grade, Integer>{
	@Autowired
	private GradeRepository gradeDAO;
	@Autowired
	private StudentRepository stuDAO;
	@Autowired
	private CourseRepository courseDAO;
	public Page<Grade> findByIdIsNull(Pageable pageable){
		return gradeDAO.findByIdIsNull(pageable);
	}
	public Page<Grade> findPageByClassIdAndCourseId(Integer classId, Integer courseId, Pageable pageable) {
		List<Stu> students = stuDAO.findByTbClassId(classId);
		Course course = courseDAO.findById(courseId).get();
		for (Stu stu : students) {
			Grade grade = gradeDAO.findByStuIdAndCourseId(stu.getId(), courseId);
			if(grade==null) {
				grade=new Grade();
				grade.setStu(stu);
				grade.setCourse(course);
				save(grade);
			}
		}
		return gradeDAO.findByStuTbClassIdAndCourseId(classId, courseId, pageable);
	}
	public Page<Grade> findbyStuId(Integer stuId, Pageable pabeable) {
		Stu stu = stuDAO.findById(stuId).get();
		Integer classId = stu.getTbClass().getId();
		List<Course> courses = gradeDAO.findCoursesByClassId(classId);
		for (Course course : courses) {
			Grade model=gradeDAO.findByStuIdAndCourseId(stuId, course.getId());
			if(model==null) {
				model=new Grade();
				model.setStu(stu);
				model.setCourse(course);
				gradeDAO.save(model);
			}
		}
		return gradeDAO.findByStuId(stuId, pabeable);
	}
	
	public List<Course> findCoursesByClassId(Integer classId) {
		return gradeDAO.findCoursesByClassId(classId);
	}
	
	public Grade findByStuIdAndCourseId(Integer stuId, Integer courseId) {
		return gradeDAO.findByStuIdAndCourseId(stuId, courseId);
	}
	public List<List<Object>> findbyStuId(Integer id) {
		Stu stu=stuDAO.findById(id).get();
		List<Course> courses=gradeDAO.findCoursesByClassId(stu.getTbClass().getId());
		List<List<Object>> cjb=new ArrayList<>();
		for (Course course : courses) {
			List<Object> list=new ArrayList<>();
			list.add(course.getName());
			Grade grade=findByStuIdAndCourseId(stu.getId(), course.getId());
			list.add(grade==null?null:grade.getGrade());
			cjb.add(list);
		}
		return cjb;
	}

}
